﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using FlyHorse.LIMS.Model;
using FlyHorse.LIMS.WinApp.Utils;
using FlyHorse.LIMS.WinApp.LanguageResource;
using System.Data.Entity;

namespace FlyHorse.LIMS.WinApp.DataManageForms.ReportSemiForms
{
    public partial class ReportSemiDetailForm : DevExpress.XtraEditors.XtraForm
    {
        BLL.GoodBll goodsBll = new BLL.GoodBll();
        BLL.ReportSemiBll reportSemiBll = new BLL.ReportSemiBll();
        BLL.ToolBll toolBll = new BLL.ToolBll();
        BLL.ReportSemiResultBll reportSemiResultBll = new BLL.ReportSemiResultBll();
        ReportSemi _report;
        List<ReportSemiResult> _resultList = new List<ReportSemiResult>();
        int _option;
        Action _ShowAllData;
        Action<IQueryable<ReportSemi>> _InitGrid;
        IQueryable<ReportSemi> _models;
        OJCB4Entities db = new OJCB4Entities();
        public ReportSemiDetailForm(Action ShowAllData)
        {
            InitializeComponent();
            _option = 1;
            textEdit_userName.Text = LoginUserUtil.LoginUser.EmpName;
            _ShowAllData = ShowAllData;

            InitCreateModel();
        }

        public ReportSemiDetailForm(ReportSemi report, IQueryable<ReportSemi> models, Action<IQueryable<ReportSemi>> InitGrid)
        {
            InitializeComponent();
            _option = 2;
            _report = db.ReportSemis.Find(report.ReportSemiID);
            InitEditModel(_report);
            _InitGrid = InitGrid;
            _models = models;
        }

        private void ReportSemiDetailForm_Load(object sender, EventArgs e)
        {
            //绑定半成品名称下拉框
            lookUpEditGoodsName.Properties.DataSource = toolBll.GetSemiGoodList().ToList();
            //绑定取样位置
            LookUpEdit_SamplingPlace.Properties.DataSource = toolBll.GetSamplingPlaceList().OrderBy(m=>m.SamplingPlaceName);
            lookUpEdit_group.Properties.DataSource = toolBll.GetProductionGropList();
            lookUpEdit_Line.Properties.DataSource = toolBll.GetProductionLineList();


            if (_option == 1)
            {
                this.Text = ResourceOverall.CreateStr;
            }
            if (_option == 2)
            {
                this.Text = ResourceOverall.EditStr;
            }

        }
        private void InitCreateModel()
        {
            this.textEdit_SendDate.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
        }

        private void InitEditModel(ReportSemi report)
        {
            lookUpEditGoodsName.Enabled = false;
            LookUpEdit_SamplingPlace.Enabled = false;
            this.lookUpEditGoodsName.EditValue = report.GoodsID;
            this.LookUpEdit_SamplingPlace.EditValue = report.SamplingPlaceID;
            //textEdit_SendPerson.Text = report.SendDate;
            textEdit_SendDate.Text = report.SendDate.ToString();
            textEdit_userName.Text = report.LoginUser.EmpName;
            textEdit_Remark.Text = report.Remark;
            this.lookUpEdit_group.EditValue = report.ProductionGroupID;
            this.lookUpEdit_Line.EditValue = report.ProductionLineID;
            _resultList = report.ReportSemiResults.ToList();
            this.dataGridControl.DataSource = _resultList;
        }

        private void ButtonItem_save_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //关闭编辑状态
            this.gridView1.CloseEditor();

            //判空
            if (this.lookUpEditGoodsName.EditValue == null)
            {
                XtraMessageBox.Show(ResourceOverall.InputNull);
                lookUpEditGoodsName.Focus();
                return;
            }
            if (this.LookUpEdit_SamplingPlace.EditValue == null)
            {
                XtraMessageBox.Show(ResourceOverall.InputNull);
                LookUpEdit_SamplingPlace.Focus();
                return;
            }
            if (textEdit_SendDate.Text == "")
            {
                XtraMessageBox.Show(ResourceOverall.InputNull);
                textEdit_SendDate.Focus();
                return;
            }
            if (this.lookUpEdit_group.EditValue == null)
            {
                XtraMessageBox.Show(ResourceOverall.InputNull);
                lookUpEdit_group.Focus();
                return;
            }
            if (this.lookUpEdit_Line.EditValue == null)
            {
                XtraMessageBox.Show(ResourceOverall.InputNull);
                lookUpEdit_Line.Focus();
                return;
            }


            if (_option == 1)
            {
                ReportSemi report = new ReportSemi();
                report.ReportSemiID = Guid.NewGuid().ToString();
                report.GoodsID = Convert.ToString(this.lookUpEditGoodsName.EditValue);
                report.Remark = this.textEdit_Remark.Text;
                report.SamplingPlaceID = Convert.ToString(this.LookUpEdit_SamplingPlace.EditValue);
                report.SendDate = Convert.ToDateTime(this.textEdit_SendDate.Text);
                report.ProductionGroupID = Convert.ToString(this.lookUpEdit_group.EditValue);
                report.ProductionLineID = Convert.ToString(this.lookUpEdit_Line.EditValue);
                report.LoginUserID = LoginUserUtil.LoginUser.LoginUserID;
                report.AddDateTime = DateTime.Now;
                report.ReportSemiResults = this._resultList;
                db.ReportSemis.Add(report);
                bool res = db.SaveChanges() > 0;
                if (res)
                {
                    _ShowAllData();
                    XtraMessageBox.Show(ResourceOverall.CreateSucceed);
                    this.Close();
                }
            }
            if (_option == 2)
            {
                _report.GoodsID = Convert.ToString(this.lookUpEditGoodsName.EditValue);
                _report.Remark = this.textEdit_Remark.Text;
                _report.SamplingPlaceID = Convert.ToString(this.LookUpEdit_SamplingPlace.EditValue);
                _report.SendDate = Convert.ToDateTime(this.textEdit_SendDate.Text);
                _report.LoginUserID = LoginUserUtil.LoginUser.LoginUserID;
                _report.ProductionGroupID = Convert.ToString(this.lookUpEdit_group.EditValue);
                _report.ProductionLineID = Convert.ToString(this.lookUpEdit_Line.EditValue);
                _report.ReportSemiResults = this._resultList;

                db.Entry(_report).State = EntityState.Modified;
                var res = db.SaveChanges() > 0;
                if (res)
                {
                    _InitGrid(_models);
                    XtraMessageBox.Show(ResourceOverall.EditSucceed);
                    this.Close();
                }
            }
        }

        private void lookUpEditGoodsName_EditValueChanged(object sender, EventArgs e)
        {
            GetEmptyResult();
        }

        private void comboBoxEdit_SamplingPlace_EditValueChanged(object sender, EventArgs e)
        {
            GetEmptyResult();
        }

        private void GetEmptyResult()
        {
            if (this.lookUpEditGoodsName.EditValue != null && this.LookUpEdit_SamplingPlace.EditValue != null)
            {
                string goodsID = Convert.ToString(this.lookUpEditGoodsName.EditValue);
                string samplingPlaceID = Convert.ToString(this.LookUpEdit_SamplingPlace.EditValue);
                var resultList = reportSemiBll.GetEmptResultList(goodsID, samplingPlaceID);
                _resultList = resultList;
                this.dataGridControl.DataSource = _resultList;
                gridView1.BeginDataUpdate();
                try
                {
                    gridView1.Columns["FormOrder"].SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;
                }
                finally
                {
                    gridView1.EndDataUpdate();
                }
            }

        }

        //private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        //{
        //    int col = e.ColumnIndex;
        //    int row = e.RowIndex;
        //    ReportSemiResult result = _resultList[row];
        //    string res = FlyHorse.LIMS.WinApp.Utils.GradeJudging.GetResultByValue(result.MinValue, result.MaxValue, result.TestValue);
        //    _resultList[row].Conclusion = res;
        //    this.dataGridControl.Refresh();
        //}

        private void ButtonItem_addTestItem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (this.lookUpEditGoodsName.EditValue == null)
            {
                XtraMessageBox.Show("样品名称必选!The name of the sample must be selected !");
                return;
            }
            if (this.LookUpEdit_SamplingPlace.EditValue == null)
            {
                XtraMessageBox.Show("取样位置必选!Sampling locations must be selected!");
                return;
            }
            FlyHorse.LIMS.WinApp.OtherForms.AddResultForm addResultForm = new OtherForms.AddResultForm(AddTestItem);
            addResultForm.ShowDialog();
        }

        private void AddTestItem(TestItem testItem, string minValue, string maxVlaue)
        {
            //查询是否存在重复项目
            foreach (var result in _resultList)
            {
                if (result.TestItemID == testItem.TestItemID)
                {
                    XtraMessageBox.Show(ResourceOverall.DataExists);
                    return;
                }
            }

            ReportSemiResult res = new ReportSemiResult();
            res.Basis = testItem.Basis;
            res.ChineseName = testItem.ChineseName;
            res.FormOrder = 999999999;
            res.ReportSemiResultID = Guid.NewGuid().ToString();
            res.MinValue = minValue;
            res.MaxValue = maxVlaue;
            res.TestItemID = testItem.TestItemID;
            res.Unit = testItem.Unit;
            _resultList.Add(res);
            string name = this.dataGridControl.DataMember;
            dataGridControl.RefreshDataSource();
            this.dataGridControl.Refresh();
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            try
            {
                string id = (string)this.gridView1.GetRowCellValue(e.RowHandle, "ReportSemiResultID");
                string minValue = null;
                string maxValue = null;
                string testValue = null;

                if (this.gridView1.GetRowCellValue(e.RowHandle, "MinValue") != null)
                {
                    minValue = this.gridView1.GetRowCellValue(e.RowHandle, "MinValue").ToString();
                }
                if (this.gridView1.GetRowCellValue(e.RowHandle, "MaxValue") != null)
                {
                    maxValue = this.gridView1.GetRowCellValue(e.RowHandle, "MaxValue").ToString();
                }
                if (this.gridView1.GetRowCellValue(e.RowHandle, "TestValue") != null)
                {
                    testValue = this.gridView1.GetRowCellValue(e.RowHandle, "TestValue").ToString();
                }



                if (!String.IsNullOrEmpty(minValue))
                {
                    Convert.ToDouble(this.gridView1.GetRowCellValue(e.RowHandle, "MinValue"));
                    minValue = Convert.ToString(this.gridView1.GetRowCellValue(e.RowHandle, "MinValue"));
                }
                if (!String.IsNullOrEmpty(maxValue))
                {
                    Convert.ToDouble(this.gridView1.GetRowCellValue(e.RowHandle, "MaxValue"));
                    maxValue = Convert.ToString(this.gridView1.GetRowCellValue(e.RowHandle, "MaxValue"));
                }
                if (!String.IsNullOrEmpty(testValue))
                {
                    try
                    {
                        Convert.ToDouble(this.gridView1.GetRowCellValue(e.RowHandle, "TestValue"));
                        testValue = Convert.ToString(this.gridView1.GetRowCellValue(e.RowHandle, "TestValue"));
                    }
                    catch (Exception ex)
                    {
                        this.gridView1.SetRowCellValue(e.RowHandle, "TestValue", null);
                        XtraMessageBox.Show(ex.Message);
                        return;
                    }
                }

                string res = FlyHorse.LIMS.WinApp.Utils.GradeJudging.GetResultByValue(minValue, maxValue, testValue);
                _resultList.Where(m => m.ReportSemiResultID == id).First().Conclusion = res;
                this.dataGridControl.Refresh();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
        }

        private void ButtonItem_DelTestItem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (this.gridView1.GetFocusedRowCellValue("ReportSemiResultID") != null)
            {
                DialogResult result = XtraMessageBox.Show(ResourceOverall.ConfirmDelete, ResourceOverall.SystemWarningStr, MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                if (result == DialogResult.OK)
                {
                    string id = (string)this.gridView1.GetFocusedRowCellValue("ReportSemiResultID");
                    _resultList = (List<ReportSemiResult>)this.dataGridControl.DataSource;
                    ReportSemiResult res = _resultList.Where(m => m.ReportSemiResultID == id).First();
                    DeleteReportResult(_resultList, res);
                    this.dataGridControl.RefreshDataSource();
                }
            }
            else
            {
                XtraMessageBox.Show(ResourceOverall.SelectNull);
            }
        }


        public void DeleteReportResult(List<ReportSemiResult> reslutList, ReportSemiResult res)
        {
            var entity = db.ReportSemiResults.Where(m => m.ReportSemiResultID == res.ReportSemiResultID).FirstOrDefault();
            if (entity != null)
            {
                db.ReportSemiResults.Remove(entity);
                db.SaveChanges();
                reslutList.Remove(res);
            }
            else
            {
                reslutList.Remove(res);
            }
        }
    }
}